import cv2

#边缘检测
def canny():
    img = cv2.imread('1.png')
    img_gray = cv2.Canny(img,100,200)
    cv2.imshow('img',img_gray)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

#人脸检测
def face_focus():
    #加载预训练的人脸检测模型
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml')
    img = cv2.imread('2.jpg')

    #转换灰度图像，提高检测精准度
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    #人脸检测
    face = face_cascade.detectMultiScale(img_gray, 1.2, 5)

    #在人脸的位置画矩形
    for (x,y,w,h) in face:
        cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

     #显示图片
    cv2.imshow('img',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


#视频人脸检测
def video_face():
    #加载人脸检测模型
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    #打开视频
    cap = cv2.VideoCapture('2.mp4')

    #获取原文件的帧率，大小
    width=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)

    #编码格式
    fource = cv2.VideoWriter_fourcc(*'mp4v')
    #创建视频文件的写入对象
    out = cv2.VideoWriter('output.mp4', fource, fps, (width, height))

    #循环逐帧处理数据
    while cap.isOpened():
        #ret:读取是否成功 frame：当前读取的数据
        ret,frame = cap.read()
        if not ret:
            break

        #转成灰图
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 人脸检测
        face = face_cascade.detectMultiScale(gray, 1.2, minNeighbors=5,minSize=(50,50))

        # 在人脸的位置画矩形
        for (x,y,w,h) in face:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

        out.write(frame)

        #时时显示
        cv2.imshow('frame',frame)

        #退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    #释放资源
    cap.release()
    out.release()
    cv2.destroyAllWindows()




if __name__ == '__main__':
    video_face()